package crawler;

import parser.*;

import java.util.List;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.HashMap;

import java.io.InputStream;
/**
 * 
 * @author Ilio Catallo, Eleonora Ciceri
 * @version: 1.0
 * 
 * Description: The class implements a flickr photo crawler
 * 
 * Date: Nov 16, 2011
 */
public class FlickrPhotoCrawler extends PhotoCrawler{
    
    public FlickrPhotoCrawler(LinkedHashMap<String, String> query, String path) {
        super("http", query, path);
        this.parser = new XMLParser();
        this.isQueryToKeep = Boolean.TRUE;
        
        this.attributes.put("id", null);
        this.attributes.put("owner", null);
        this.attributes.put("secret", null);
        this.attributes.put("server", null);
        this.attributes.put("farm", null);
        this.attributes.put("title", null);
        this.attributes.put("ispublic", null);
        this.attributes.put("isfriend", null);
        this.attributes.put("isfamily", null);
        
        this.navigationPath.add("photo");
    }
    
    @Override
    protected List<String> composeURLs(List<HashMap<String, String>> responseAttributes) {
        // Variables
        List<String> URLs = new ArrayList<String>();
        
        for (HashMap<String, String> currAttributes : responseAttributes){
            
            String URL = "http://farm" + currAttributes.get("farm") + 
                         ".static.flickr.com/" + currAttributes.get("server") 
                         + "/" + currAttributes.get("id") + 
                         "_" + currAttributes.get("secret") + ".jpg";
            
            URLs.add(URL);
           
        }
        
        return URLs;
    }

    @Override
    protected List<HashMap<String, String>> findIncrAttributes() {
        // Variables
        HashMap<String, String> attributes = new HashMap<String, String>();
        List<String> navigationPath = new ArrayList<String>();
        List<HashMap<String, String>> incrementAttributes = new ArrayList<HashMap<String, String>>();
        
        navigationPath.add("photos");
        attributes.put("pages", null);
        
        this.restClient.executeQuery(this.query);
        InputStream responseContent = restClient.getResponseContent();
       
        this.parser.setNavigationPath(navigationPath);
        this.parser.setAttributes(attributes);
        this.parser.parse(responseContent);
        
        List<HashMap<String, String>> parsedResponse = this.parser.getResponseAttributes();
        Integer numPages = Integer.parseInt(parsedResponse.get(0).get("pages"));
        
        for (int i = 0; i < numPages; i++) {
            HashMap<String, String> currPage = new HashMap<String, String>();
            currPage.put("page", Integer.toString(i+1));
            incrementAttributes.add(currPage);
        }
    
        return incrementAttributes;
    }

}